package com.itzxx.huazhun.ui.record.local

import androidx.lifecycle.viewModelScope
import com.itzxx.huazhun.data.dao.CollectionEntity
import com.itzxx.huazhun.data.dao.DbHelper
import com.itzxx.huazhun.data.model.EventMessage
import com.itzxx.huazhun.data.model.EventType
import com.itzxx.huazhun.data.model.RecordChildBean
import com.itzxx.huazhun.data.repository.HttpRequestCoroutine
import com.itzxx.huazhun.ui.record.valuation.RecordValuationLocalActivity
import com.itzxx.huazhun.utils.ExcelUtil
import com.itzxx.library_base_ktx.base.viewmodel.BaseViewModel
import com.itzxx.library_base_ktx.callback.livedata.event.EventLiveData
import com.itzxx.library_base_ktx.ext.request
import com.itzxx.library_base_ktx.ext.util.loge
import com.itzxx.library_base_ktx.state.ListDataUiState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus

class RecordLocalViewModel : BaseViewModel() {
    //列表数据刷新
    val listDataUiStateLiveData = EventLiveData<ListDataUiState<CollectionEntity>>()

    val uploadRecodLiveData = EventLiveData<CollectionEntity>()

    val sceneTypeLiveData = arrayOf("高温灭菌", "清洗消毒", "真空泄漏")

    //默认第1个
    var currentCheckSceneTypePosition = 0

    /**
     * 获取数据列表
     */
    fun getList(isRefresh: Boolean) {
        request({
            HttpRequestCoroutine.getCollectionRecordList()
        }, {
            val listDataUiState =
                ListDataUiState(
                    isSuccess = true,
                    isRefresh = isRefresh,
                    isEmpty = it.isEmpty(),
                    hasMore = false,
                    isFirstEmpty = it.isEmpty(),
                    listData = it
                )
            listDataUiStateLiveData.postValue(listDataUiState)
        }, {
            toast(it.errorMsg)
        })
    }

    fun uploadProbeCollection(collectionEntity: CollectionEntity) {
        //开始采集
        loadingChange.showDialog.postValue("上传数据中...")
        baseContext.value?.let { that ->

//            viewModelScope.launch (Dispatchers.IO){
//                collectionEntity.recordId = "222"
//                val exportExcelPath = ExcelUtil.exportExcel(
//                    that,
//                    collectionEntity
//                )
//            }
            request({
                HttpRequestCoroutine.uploadProbeCollection(
                    that, collectionEntity
                )
            }, {
                loadingChange.dismissDialog.postValue(false)
                "上传成功".loge()
                uploadRecodLiveData.postValue(collectionEntity)
                EventBus.getDefault().post(EventMessage(EventType.UPLOAD_RECORD, ""))
            }, {
                loadingChange.dismissDialog.postValue(false)
                "上传失败".loge()
                if(it.errorMsg.contains("记录已存在")){
                    uploadRecodLiveData.postValue(collectionEntity)
                    collectionEntity.state = 1
                    viewModelScope.launch {
                        withContext(Dispatchers.IO){
                            DbHelper.init().getCollectionDao().update(collectionEntity)
                        }
                    }
                }
                toast("上传失败：${it.errorMsg}")
            })
        }
    }

    fun onValuateEvent(list: List<CollectionEntity>) {
        val tempList = arrayListOf<Int>()
        list.forEach {
            if (it.isCheck) {
                tempList.add(it.id.toInt())
            }
        }
        if (tempList.isEmpty()) {
            toast("请选择采集记录")
            return
        }
        var sceneType = 2
        when (sceneTypeLiveData[currentCheckSceneTypePosition]) {
            "高温灭菌" -> sceneType = 2
            "清洗消毒" -> sceneType = 7
            "真空泄漏" -> sceneType = 10
        }
        //真空只能有一条
        if (sceneType == 10 && tempList.size > 1) {
            toast("真空泄露不可选择多条数据")
            return
        }
        baseContext.value?.let {
            RecordValuationLocalActivity.startActivity(
                it,
                sceneType,
                tempList
            )
        }
    }
}